var rosObj = null

var rosUrl = ""

var topic = {
  infrared: null,
}

var callBackFun = {
  infrared: null,
}

// 心跳状态 1 存在 0 不存在
var infraredHeartStatus = 0;

exports.install = function (Vue, options) {
  Vue.prototype.inraredRosInit = function (data) {
    console.log("inrared ros init");
    rosObj = new ROSLIB.Ros();
    monitorsHeart();
    return rosObj;
  }

  Vue.prototype.inraredRosConnect = function (data) {
    if (data && data.url) {
      console.log("inrared ros connect");
      rosObj.connect(data.url);
      rosUrl = data.url
      return true;
    } else {
      return false;
    }
  }

  Vue.prototype.inraredRosClose = function (data) {
    console.log("inrared ros close");
    rosObj.close();
    return true;
  }

  Vue.prototype.inraredRosConnectStatus = function (data) {
    console.log("inrared ros connected");
    return rosObj;
  }

  Vue.prototype.inraredRosOnConnection = function (data) {
    rosObj.on("connection", function () {
      console.log("inrared ros connection");
      rosUnsubscribes()
      rosSubscribes()
    });
    return true;
  }

  Vue.prototype.inraredRosOnClose = function (data) {
    rosObj.on("close", function () {
      console.log("inrared ros close");
    });
    return true;
  }

  Vue.prototype.inraredRosOnError = function (data) {
    rosObj.on("error", function (error) {
      console.log("inrared ros error");
    });
    return true;
  }

  /**
   *   红外回调
   *
   *   @param {*} callBack 回调函数
   */
  Vue.prototype.infraredCallBack = function (callBack) {
    if (callBack instanceof Function) {
      callBackFun.infrared = callBack
    } else {
      callBack({
        status: 1001,
        message: "错误：指定类型为Function"
      })
    }
  }
  Vue.prototype.infraredUnCallBack = function () {
    callBackFun.infrared = null;
  }
};

/**
 *  订阅所有
 *
 */
function rosSubscribes() {
  rosInfraredSubscribe();
}

/**
 *  取消订阅所有
 *
 */
function rosUnsubscribes() {
  rosInfraredUnsubscribe();
}

/**
 *  红外声明和订阅
 *  
 */
function rosInfraredSubscribe() {
  // 声明
  topic.infrared = new ROSLIB.Topic({
    ros: rosObj,
    name: "/thermal/image_proc/compressed",
    messageType: "sensor_msgs/CompressedImage",
    queue_size: 0
  });
  // 订阅
  topic.infrared.subscribe(message => {
    infraredHeartStatus = 1;
    if (callBackFun.infrared) {
      callBackFun.infrared(message)
    }
  });
}

/**
 *   红外取消订阅
 *
 */
function rosInfraredUnsubscribe() {
  if (topic.infrared) {
    topic.infrared.unsubscribe();
  }
}

function monitorsHeart() {
  setInterval(() => {
    if (infraredHeartStatus == 1) {
      infraredHeartStatus = 0;
    } else {
      console.log("ros infrared heartStatus", infraredHeartStatus)
      rosObj.connect(rosUrl);
    }
  }, 3000);
}

